package logic

import (
	"context"
	"errors"
	"short-vid-joy/models/cache"
	"short-vid-joy/models/mysql"
	"short-vid-joy/pkg"
	"short-vid-joy/shortrpc/internal/svc"
	"short-vid-joy/shortrpc/shortrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RePasswordLogic {
	return &RePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RePasswordLogic) RePassword(in *shortrpc.RePasswordRequest) (*shortrpc.RePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User

	if err := findUser.FindUserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("用户不存在")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result == "" {
		return nil, errors.New("请发送验证码")
	}

	if in.SmsCode != result {
		return nil, errors.New("验证码错误,请重新输入")
	}

	if in.NewPassword != in.AckPassword {
		return nil, errors.New("两次密码不一致,请重新输入")
	}

	findUser.Password = pkg.Md5(in.AckPassword)

	if err := findUser.UpdatePassword(mysql.DB); err != nil {
		return nil, err
	}

	return &shortrpc.RePasswordResponse{
		UserId: int64(findUser.ID),
	}, nil
}
